#!/bin/bash
set -e

while getopts  "w:c:p:t" opts
do
	case  $opts  in
	w)
		window=$OPTARG
		;;
	c)
		c_const=$OPTARG
		;;
	p)
		out_prefix=$OPTARG
		;;
	t)
		T=1
		;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$2" ]; then
	echo `basename $0 ` '[-w window_size] [-c c_const] [-p out_prefix] [-t] <sample.bam> <control.bam>'
	exit 1
fi

#-----------------------------------------------
#-----------------------------------------------
. /mnt/ilustre/app/medical/tools/.var #---------
#-----------------------------------------------
#-----------------------------------------------
log=.log
if [ ! -e "$log" ]; then
	:> $log
fi

if [ -z "$window" ]; then
	window=200000
fi

if [ -z "$out_prefix" ]; then
	out_prefix=1
fi

if [ -z "$c_const" ]; then
	c_const=100
	echo $_const 2>>$log 1>&2
fi

if [ -z "T" ]; then
	corr=T
else 
	corr=F
fi




bai1=$1.bai
bai2=$2.bai
base1=`basename $1 .bam`
base2=`basename $2 .bam`
if [ ! -e "$bai1" ]; then
	
	echo samtools index $1 2>>$log 1>&2
	samtools index $1
fi
if [ ! -e "$bai2" ]; then
	
	echo samtools index $1 2>>$log 1>&2
	samtools index $1
fi

chrom=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,X,Y

echo 2>>$log 1>&2
echo 2>>$log 1>&2
echo readCounter sample 2>>$log 1>&2
echo window $window 2>>$log 1>&2
echo $1 2>>$log 1>&2
readCounter -c $chrom -w $window -s $1 > $out_prefix.$window.1.seg 2>>$log

echo 2>>$log 1>&2
echo 2>>$log 1>&2
echo readCounter control 2>>$log 1>&2
echo window $window 2>>$log 1>&2
echo $2 2>>$log 1>&2
readCounter -c $chrom -w $window -s $2 > $out_prefix.$window.2.seg 2>>$log



cat $out_prefix.$window.1.seg |cut -f 2,3,5 > $out_prefix.1.rc.txt
cat $out_prefix.$window.2.seg |cut -f 5 > $out_prefix.2.rc.txt
paste $out_prefix.1.rc.txt $out_prefix.2.rc.txt | awk '$3 != 0 || $4 != 0' > $out_prefix.rc.txt


echo 2>>$log 1>&2
echo start mhmm 2>>$log 1>&2
echo c_const $c_const >> $log
Rscript ${tools_path}/script/mhmm0810.r \
--args \
$out_prefix.rc.txt \
$out_prefix \
$c_const \
$corr \
2>>$log 1>&2

echo end mhmm >> $log

exit 0



